package cn.wolfcode.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/thread3")
public class LockController {
    //todo 线程

    private ReentrantLock lock = new ReentrantLock();
    private ReentrantLock lock2 = new ReentrantLock(true);//公平锁
    private Integer number = 20;


    public void sale(){

        lock.lock();
        //lock.tryLock(1, TimeUnit.SECONDS);

        if (number <= 0) {
            System.out.println("票已售罄！");
            lock.unlock();
            return;
        }

        try {
            Thread.sleep(200);
            number--;
            System.out.println(Thread.currentThread().getName() + "买票成功，当前剩余：" + number);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        LockController ticket = new LockController();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "AAA").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "BBB").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "CCC").start();

    }
}
